package com.wy2cloud.sample.redisdemo.controller;

import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.ListOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.wy2cloud.sample.redisdemo.vo.SystemUser;

@RestController
public class HomeController {
	
	private static final String key_prefix="test:com.xo68:";
	private static final Integer expire_timeout=300;
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	
	@Resource
	private HashOperations<String, String, SystemUser> hashOperations;
	
	@Resource
    private ListOperations<String, SystemUser> listOperations;

	@GetMapping({"/",""})
	public String index(@RequestParam(name="key") String key) {
		if(stringRedisTemplate.hasKey(key_prefix+key)) {
			stringRedisTemplate.expire(key_prefix+key, expire_timeout, TimeUnit.SECONDS);
			return stringRedisTemplate.opsForValue().get(key_prefix+key);
		}
		return "success";
	}
	
	@PostMapping("/add")
	public String add(@RequestParam(name="key") String key,
			@RequestParam(name="value") String value) {
		stringRedisTemplate.opsForValue().set(key_prefix+key, value, expire_timeout, TimeUnit.SECONDS);
		return "success";
	}
	
	@PostMapping("/addHash")
    public String addJson(@RequestParam(name="key") String key,
            @RequestBody SystemUser value) {
	    hashOperations.put("hash:cn.xo68:", key, value);
	    stringRedisTemplate.expire("hash:cn.xo68:", expire_timeout, TimeUnit.SECONDS);
        //stringRedisTemplate.opsForValue().set(key_prefix+key, value, expire_timeout, TimeUnit.SECONDS);
        return "success";
    }
	
	@PostMapping("/addList")
    public String addList(@RequestParam(name="key") String key,
            @RequestBody SystemUser value) {
	    listOperations.leftPush("list:cn.xo68:"+key, value);
        stringRedisTemplate.expire("list:cn.xo68:"+key, expire_timeout, TimeUnit.SECONDS);
        //stringRedisTemplate.opsForValue().set(key_prefix+key, value, expire_timeout, TimeUnit.SECONDS);
        return "success";
    }
}
